// pages/imageProof/imageProof.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    files: ["http://tidukeji.cn/faceImage/faceMan.png", "http://tidukeji.cn/faceImage/faceWoman.png"],
    originalfilesurl: [],
    uploadfiles: [],
    type: "",
    usernumber: null,
    name: "",
    employer: "",
    faceimage: "",
    type: "",
    dayTime: null,
    loading:1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options);
    let originalfilesurlTemp = this.data.originalfilesurl;
    let uploadfilesTemp = this.data.uploadfiles;
    wx.request({
      url: app.baseUrl + '/WeChat/weChatSystem/getPersonImage',
      method: 'POST',
      data: {
        userId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
        console.log(res, "acacsa")
        if (res.data.status == "update") {
          originalfilesurlTemp.push(res.data.data[0].faceimage)
          uploadfilesTemp.push(res.data.data[0].faceimage)
          this.setData({
            usernumber: res.data.data[0].usernumber,
            name: res.data.data[0].name,
            employer: res.data.data[0].employer,
            originalfilesurl: originalfilesurlTemp,
            uploadfiles: uploadfilesTemp,
            type: res.data.status,
            dayTime: res.data.data[0].dayTime,
            hide: true
          },()=> {
            this.setData({
              loading: 0,
            })
            if (this.data.dayTime > 0) {
              wx.showToast({
                title: "今日更新次数已满",
                icon:'none',
                // image: "/images/attention.png",
                duration: 1500
              })
            }
            })

        } else {
          this.setData({
            type: res.data.status,
            loading:0
          })
        }
      },
      fail: res => {
        wx.showToast({
          title: "初始化失败",
          image: "/images/error.png"
        })
      }

    })

  },

  previewImage: function(e) {
    console.log(e);
    wx.previewImage({
      current: this.data.files[e.currentTarget.id], // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  deleteImage: function(e) {
    console.log(e);
    let targetIndex = e.currentTarget.dataset.index
    let target = this.data.uploadfiles[targetIndex]
    let temp = []
    let tempUrl = []
    let filesLength = this.data.uploadfiles.length
    for (let i = 0; i < this.data.uploadfiles.length; i++) {
      if (i != targetIndex) {
        temp.push(this.data.originalfilesurl[i])
        tempUrl.push(this.data.uploadfiles[i])
      }
    }

    wx.showActionSheet({
      itemList: ['删除这张照片'],
      success: res => {
        if (!res.cancel) {
          this.setData({
            originalfilesurl: temp,
            uploadfiles: tempUrl,
          })
          console.log(target.split("image/")[1]);
          wx.request({
            url: app.baseUrl + '/WeChat/weChatSystem/deleteFile',
            method: 'POST',
            data: {
              filename: target.split("image/")[1]
            },
            dataType: 'json',
            success: res => {
              if (temp.length < 1) {
                this.setData({
                  hide: false
                })
              }
            }
          })
        }
      }
    })
  },

  formSubmit: function(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let usernumber = e.detail.value.number
    let name = e.detail.value.name
    let employer = e.detail.value.department
    if (!usernumber || !name || !employer || this.data.originalfilesurl.length<1){
      wx.showToast({
        title: "请填写完整信息",
        image: "/images/error.png"
      })
    }else{
      wx.request({
        url: app.baseUrl + '/WeChat/weChatSystem/personImageUpload',
        method: 'POST',
        data: {
          usernumber: usernumber,
          userId: app.globalData.userId,
          name: name,
          employer: employer,
          department: app.globalData.departmentId,
          faceimage: this.data.uploadfiles[0],
          type: this.data.type
        },
        dataType: 'json',
        success: res => {
          console.log(res, "acascasc")
          if (res.data == "exist") {
            wx.showToast({
              title: "编号已存在",
              image: "/images/error.png"
            })
          } else if (res.data == "success") {
            wx.reLaunch({
              url: '/pages/mine/mine'
            })

            wx.showToast({
              title: "认证成功",
              image: "/images/star_fill.png"
            })

          } else {
            wx.showToast({
              title: "认证失败",
              image: "/images/error.png"
            })
          }
        },
        fail: res => {
          wx.showToast({
            title: "认证失败",
            image: "/images/error.png"
          })
        }
      })
    }
  },

  chooseImage: function(e) {
    var that = this;

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showLoading({
          title: "图片上传中",
          mask: true
        })
        let tempImg = res.tempFilePaths
        console.log(res, "sdvsdvs")
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.baseUrl + '/WeChat/weChatSystem/fileUpload',
            filePath: res.tempFilePaths[i],
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              console.log(1)
              console.log(res)
              if (res.statusCode == 500) {
                wx.showToast({
                  title: "图片上传失败",
                  image: "/images/error.png"
                })
              } else {
                wx.showToast({
                  title: "上传成功"
                })
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                  originalfilesurl: that.data.originalfilesurl.concat(tempImg[i])
                })
                if (that.data.originalfilesurl.length == 1) {
                  that.setData({
                    hide: true
                  })
                }
                this.data.uploadfiles.push(res.data)
              }
            },
            fail: res => {
              console.log(2)
              console.log(res)
              wx.showToast({
                title: "图片上传失败",
                image: "/images/error.png"
              })
            }
          })
        }
      }
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },


})